<template>
  <div class="live-room-box">   
    <component :is='isLsPoScreen' :roomInfo='roomInfo' @sendFather='childCallBack'></component>
    <!--私密直播-->
    <Private v-if='isPrivate' :privateWords='roomInfo.roomInfo.privateWords' @sendFather='childCallBack' type='liveCom'></Private>
    <!--白名单组件-->
    <WhiteListCom v-if='isWhiteList' type='liveCom' :roomVideoInfo='roomInfo'  :whiteListTopTip='whiteListTopTip' :whiteListInputText='whiteListInputText' @sendFather='childCallBack' />
    <!-- 非白名单提示页 -->
    <WhiteTip v-if="isWhiteTip" :type="WhiteType"></WhiteTip>
    <!-- 关播提示 组件 -->
    <liveOffTip :roomInfo='roomInfo.roomInfo' v-if="tipOff" :videoMakeTip="videoMakeTip"></liveOffTip>
    <!-- 中信信用卡 关播提示 组件 -->
    <LiveEndPop v-if='isLiveEndPop' :roomInfo='roomInfo.roomInfo'></LiveEndPop>
    <!-- 违规提示组件 -->
    <IllegalTips v-if="isIllegalTips" />
    <!-- 弹窗提示 -->
    <DialogD :isShow="isShow" :mode="mode" @changeShowDialog="changeShowDialog">{{tips}}</DialogD>
    <!-- app手机登录验证兜底组件 -->
    <VerifyAppLogin :modeType = 'appLoginState' v-if="isVerifyAppLogin" />
  </div>
</template>
<script>
  import LscreenLive from './components/landscapeLiveCom.vue'; //横屏直播
  import PortraitScreenLive from './components/portraitScreenCom.vue'; //竖屏直播
  import Private from "@/components/privateComponent";
  import liveOffTip from './components/liveOffTip.vue'; //关播提示
  import LiveEndPop from '@/components/zxxykzx/liveEndPop.vue'
  import WhiteListCom from '@/components/whiteListCom'; //白名单组件
  import WhiteTip from '@/components/WhiteTip'; //腾讯会议非白名单提示页
  import IllegalTips from '@/components/illegalTips'; //违规提示
  import { checkLiveMaxUvLimit, checkWhitelist } from '@/util/api.js';
  import VerifyAppLogin from '@/components/verifyAppLogin' //手机登录验证兜底提示页面
  export default {
    components: {
      LscreenLive, //横屏直播
      PortraitScreenLive, //竖屏直播
      Private, //私密直播
      liveOffTip,
      LiveEndPop,
      WhiteListCom, //白名单组件
      IllegalTips,
      VerifyAppLogin,
      WhiteTip,//腾讯会议非白名单提示页
    },
    data() {
      return {
        isLiveEndPop: false, //中信信用卡弹窗
        isLsPoScreen: '', //横屏竖屏
        roomId: this.$route.params.roomid, //房间id
        isPrivate: false, //私密直播
        isWhiteList: false, //白名单
        whiteListInputText: '', //白名单提示文字
        whiteListTopTip: '', //白名单头部提示文字
        roomInfo: {}, //房间信息
        tipOff: false, //关播提示
        videoMakeTip: null, //视频制作提示
        isIllegalTips: false, //违规提示
        isShow: false,
        tips: '',
        appLoginState:'',//phoneLogin 手机号登录观看  riskPrivate  私募微服务
        isVerifyAppLogin:false,
        isWhiteTip:false,
        WhiteType: false,//用于标识腾讯会议非白名单提示页的类型
      }
    },
    computed: {
      gsTipShow() { //国盛风险提示开关
        return this.$store.state.showGsTip;
      },
      appVisible() {
        return this.$store.state.appVisible
      }
    },
    watch:{
      '$store.state.appVisible'(val){
        if(val &&  this.$channel == 'zxjt'){
          if(this.appLoginState === 'phoneLogin'){//手机验证未登录返回  
            // fun.appZxjtLoginInfoCallBack().then(res=>{//可以拿到登录返回值
            //     if(res === 'phoneLogin' || res === 'riskPrivate'){//手机号登录 || 资金账号登录
            //         this.isVerifyAppLogin = false;
            //     }else if(res === 'logOut'){
            //         this.isVerifyAppLogin = true;
            //     }
            // })
          }else if(this.appLoginState === 'riskPrivate'){//私募微服务

          }
        }
      },
      '$store.state.isYk'(val){
          if(!val && window.terminal.isZxjtApp && this.appLoginState === 'phoneLogin'){//非游客
            this.isVerifyAppLogin = false;
            this.rendLive()
          }
      }
    },
    async created() {
      const roomDetail = await this.getRoomInfo();
      const { title, anchor, roomId, roomStatus } = roomDetail;
      this.$store.commit("setRoomDetail", roomDetail);
      document.title = title; // 更新页面title（神策）
      // 神策打点（进入房间）
      roomStatus !== "2" && $sensorsTrack('liveBroadcast_PageView', {
        user_nickname: this.$store.state.userInfo.nickname, 
        live_room_id: roomId,
        live_room_name: title,
        live_room_status: ['预告', '直播中', "回看"][roomStatus],
        live_room_creator: anchor,
      });
    },
    mounted() {
      this.$store.dispatch("hideNav");
    },
    beforeDestroy() {
      document.title = '中信建投'; // 更新页面title（神策）
    },
    destroyed() {
      this.$store.dispatch("setShowGsTip", false);
      window.sessionStorage.setItem(`${this.$channel}invitCard`, JSON.stringify([])); //退出当前直播间 邀请卡数据置空
      this.$store.commit('setAppVisible', true)
    },
    methods: {
    async rendLive() {
      //  isprivate  1 私密直播   2 老版本白名单  3 手机登录观看  5新版本白名单库
      const { roomInfo, roomInfo: { mode, maxUvNum, roomStatus, sid, channel, isprivate, partnerType, isRestrict, roomExt2}, ext: { whiteCheck, whiteData } } = this.roomInfo;
      const { enRc, rcType, qaId, rcId } = roomExt2 || {};
      let extParam = sessionStorage.getItem('extParam')
      let source = sessionStorage.getItem('source')
      // 1:匹配是否超过最大人数 
      if (maxUvNum > 0) {
        try {
          const checkPass = await checkLiveMaxUvLimit(this.roomId)
          const { code } = checkPass.data;
          if (code != '000000') {//校验不通过
            fun.toastMessage('当前直播间观看人数已达到最多人数限制，请查看其他直播')
            this.$router.replace(`/${this.$channel}/home`);
            return
          }
        } catch (error) {

        }
      }
      // 2:白名单
      let plat = await fun.initSourcePlat()
      if (source === 'hly_mini' && !extParam && plat ==='mini') {//来源如果是会路演小程序但是无extParam
        this.isWhiteTip = true
        this.WhiteType = true
        return
      }
      if (isprivate == 2 || isprivate == 5) {
        if (!whiteCheck) {//true  验证通过  false 为不通过
          if (extParam && source === 'hly_mini' && plat === 'mini') {//来源是会路演小程序而且有extParam，校验extParam
            this.tencentWhite()
          } else {//不存在extParam，走之前白名单逻辑
            this.whiteListInputText = whiteData?.inputText || '请输入观看密码';
            this.whiteListTopTip = whiteData?.tip || '欢迎观看本直播';
            this.isWhiteList = true;
            return
          }
        }
      }
      // 3:私密直播   (isRestrict 是否第一次验证   0第一次  1非第一次)
      if (isprivate == '1' && isRestrict == '0') {
        this.isPrivate = true;
        return
      }
      // 4:手机登录观看
      if (isprivate == 3 && this.$store.state.isYk) {
        if (window.terminal.isZxjtApp) {
          this.appLoginState = 'phoneLogin'; 
          this.isVerifyAppLogin = true;                  
          console.log('app拉起手机登录前');
          fun.ykDisposeFun() // 手机登录
          return
        } else {
          //进入直播间从底部弹出手机号码验证
        }
      }
       //私募跳转过来?passEnRc=true
      if (this.$route.query.passEnRc) {
        if (mode == 0) { //默认横屏
          this.isLsPoScreen = 'LscreenLive'
        } else if (mode > 0) { //竖屏   1全屏  2  全屏半
          this.isLsPoScreen = 'PortraitScreenLive'
        }
        return
      }
      // 5:私募验证 (最后一步私募)
      if( enRc ){//私募开关开
        if( rcType == 0 || rcType == 1 || rcType == 4 ){//rcType  0 普通私募 1 私募风控  4 带货
          let source = sessionStorage.getItem('source')
          let targetUrl = encodeURIComponent(fun.getCurPageUrl('live',this.roomId,true));
          let url = `${config.smTargetUrl}${this.$channel}/login?bizId=${this.roomId}&bizToken=${this.$token}&bizUtil=room&partnerId=${this.$store.state.userInfo.un}&rcType=${rcType}&qaId=${qaId}&rcId=${rcId}&targetUrl=${targetUrl}&backUrl=${config.smBackUrl}&source=${source || this.$source}`;
          if (window.terminal.isZxjtApp) {
              const obj = {
                'link':url,
                'linkType':1
              }
              this.appLoginState = 'riskPrivate';
              this.isVerifyAppLogin = true;
              fun.zxjtAppLink(obj)
            } else {
              window.location.replace(url)
            }
        }  
      }else{
        if (mode == 0) { //默认横屏
          this.isLsPoScreen = 'LscreenLive'
        } else if (mode > 0) { //竖屏   1全屏  2  全屏半
          this.isLsPoScreen = 'PortraitScreenLive'
        }
      }     
    },
      getRoomInfo() {
        return new Promise(resolve => {
          this.$http.get(`/h5live/getRoomInfo?roomId=${this.roomId}&newRoom=true`).then(async res => {
            const { code , data } = res.data;
            if( code === '000000' ){
              this.roomInfo = data;             
              const { roomInfo , roomInfo : { mode ,roomStatus, sid ,channel }} = data;
              resolve(roomInfo);
              window.sessionStorage.setItem('mode', mode)
              //roomStatus  0预告 1开播  2 关播
              if( roomStatus == 2 ){
                this.checkBackVideo( sid );
              }else {
                if(channel == this.$route.params.channel ){
                  this.rendLive();
                }else {
                  console.log('进入直播间机构号不匹配')
                  fun.toastMessage('进入直播间机构号不匹配')
                  setTimeout(()=>{
                    fun.liveBackFun();
                  },2000)
                }
              }
            }else{
              console.log('getRoomInfo 接口code错误')
              fun.toastMessage('getRoomInfo api  error')
              setTimeout(()=>{
                fun.liveBackFun();
              },2000)
            }
          }, err => {})
        })
      },
      checkBackVideo(sid) { //跳转回看
        this.$http.get("/h5live/getBackId", {
          params: {
            sceneId: sid, //场次id
          }
        }).then(
          res => {
            if (res.data.code == "000000") {
              console.log("跳转到视频回看页面")
              if (res.data.data.id) {
                let extParam = sessionStorage.getItem('extParam')
                let source = sessionStorage.getItem('source')
                if(source && extParam){
                  this.$router.replace(`/${this.$channel}/liveBack/${res.data.data.id}?extParam=${extParam}&source=${source}`);
                }else{
                  this.$router.replace(`/${this.$channel}/liveBack/${res.data.data.id}`);
                }                
              } else {
                console.log("返回成功但返回id为空")
              }
            } else if (res.data.code == "100013") { //视频制作中
              if (this.$channel === 'zxxykzx') {
                this.isLiveEndPop = true
                return
              }
              this.videoMakeTip = true
              this.tipOff = true
            } else if (res.data.code == "100012") { //视频下架
              if (this.$channel === 'zxxykzx') {
                this.isLiveEndPop = true
                return
              }
              this.videoMakeTip = false
              this.tipOff = true
            }
          },
          err => {
            console.log(err);
          }
        );
      },
      childCallBack(data) {
        switch (data.type) {
          case 'successWhiteList': //关闭白名单验证
            this.isWhiteList = false;
            this.roomInfo.ext.whiteCheck = true;
            this.rendLive();
            break;
          case 'successPrivate': ///关闭私密直播
            this.isPrivate = false;
            this.roomInfo.roomInfo.isprivate = 0
            this.rendLive();
            break;
          case 'closeLiveEnd': //正常停播消息
            this.getRoomInfo()
            break;
          case 'violations': // 违规停播
            this.$store.dispatch("globalMask", {
              isShow: true,
              bgColor: 'rgba(0,0,0,.4)'
            });
            this.isIllegalTips = true;
            break;
          default:
            break;
        }
      },
      //腾讯会议直播间校验白名单逻辑
      async tencentWhite() {
        let extParam = sessionStorage.getItem('extParam')
        const params = {
          extParam,
          roomId: this.$route.params.roomid,
          type: '1', //1直播间 2视频库 3 付费课程(建投)
          vid: this.$route.params.id,
        };
        try {
          const dataMsg = await checkWhitelist(params)
          const { code, msg } = dataMsg.data;
          if (code !== "000000") {//验证不成功，展示非白名单提示页
            this.isWhiteTip = true
            return
          }
        } catch (error) {
          console.log(error);
        }
      }
    }
  }
</script>

<style scoped="scoped" lang="less">
  .live-room-box {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: white;
  }
</style>
